<template>
	<div class="app-container">
		<el-form class="queryForms" :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
			<el-form-item label="工段名称" prop="workshopSectionName">
				<el-input v-model="queryParams.workshopSectionName" placeholder="请输入工段名称" clearable @keyup.enter.native="handleQuery" maxlength="20" show-word-limit  />
			</el-form-item>
			<el-form-item label="状态" prop="state">
				<el-select v-model="queryParams.state" placeholder="状态" clearable>
					<el-option v-for="dict in dict.type.default_status" :key="dict.value" :label="dict.label" :value="dict.value" />
				</el-select>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
				<el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
			</el-form-item>
		</el-form>

		<el-row :gutter="10" class="mb8">
			<el-col :span="1.5">
				<el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['erp:workshopSection:add']">新增</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button type="danger" icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['erp:workshopSection:remove']">删除</el-button>
			</el-col>
			<right-toolbar @changeTableData="changeTableData" menuNames="workshopSelection70" :showSearch.sync="showSearch" @queryTable="getList" :columns.sync="columns" perm="erp:workshopSection:list"></right-toolbar>
		</el-row>

		<div :class="eleTabTop <= 85 ? 'eleTab' : ''" class="informationTab" ref="eleTab">
			<el-table ref="table" @row-click="row_click" v-loading="loading" :data="workshopSectionList" @selection-change="handleSelectionChange" border height="100%">
				<el-table-column type="selection" width="55" align="center" />
				<el-table-column label="序号" align="center" type="index" width="55" />
				<el-table-column label="生产车间" prop="workshopName" min-width="150" :show-overflow-tooltip="true" v-if="columns[0].visible" />
				<el-table-column label="工段名称" prop="workshopSectionName" min-width="150" :show-overflow-tooltip="true" v-if="columns[1].visible" />
				<el-table-column label="工段长" prop="workshopSectionChiefName" min-width="150" :show-overflow-tooltip="true" v-if="columns[2].visible" />
				<el-table-column label="状态" align="center" prop="state" min-width="150" :show-overflow-tooltip="true" v-if="columns[3].visible">
					<template slot-scope="scope">
						<el-switch v-model="scope.row.state" active-value="1" inactive-value="0" @change="handleStatusChange(scope.row)"> </el-switch>
					</template>
				</el-table-column>
				<el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="200">
					<template slot-scope="scope">
						<el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['erp:workshopSection:edit']">修改</el-button>
						<el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['erp:workshopSection:remove']">删除</el-button>
						<el-dropdown size="mini" @command="command => handleCommand(command, scope.row)" v-hasPermi="['erp:workshopSection:userSet', 'erp:workshopSection:userList']">
							<el-button size="mini" type="text" icon="el-icon-d-arrow-right">更多</el-button>
							<el-dropdown-menu slot="dropdown">
								<el-dropdown-item command="handleSetting" v-hasPermi="['erp:workshopSection:userSet']">人员配置</el-dropdown-item>
								<el-dropdown-item command="handleUserList" v-hasPermi="['erp:workshopSection:userList']">人员列表</el-dropdown-item>
							</el-dropdown-menu>
						</el-dropdown>
					</template>
				</el-table-column>
			</el-table>
		</div>

		<pagination menuNames="Pagination73" v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

		<!-- 添加或修改工段对话框 -->
		<el-dialog :title="title" :visible.sync="open" width="900px" append-to-body v-dialogDrag>
			<el-form ref="form" :model="form" :rules="rules" label-width="80px" class="add-form2">
				<el-form-item label="生产车间" prop="workshopId">
					<el-select v-model="form.workshopId" placeholder="请选择" @change="changeworkshop">
						<el-option v-for="dict in dict.type.default_workcar" :key="dict.value" :label="dict.label" :value="dict.value"> </el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="工段名称" prop="workshopSectionName">
					<el-input v-model="form.workshopSectionName" placeholder="请输入工段名称" maxlength="20" show-word-limit  />
				</el-form-item>
				<el-form-item label="状态" prop="state">
					<el-radio-group v-model="form.state">
						<el-radio v-for="dict in dict.type.default_status" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
					</el-radio-group>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="submitForm">确 定</el-button>
				<el-button @click="cancel">取 消</el-button>
			</div>
		</el-dialog>
		<!-- 人员配置弹框 -->
		<el-dialog title="人员配置" :visible.sync="openUser" width="1200px" append-to-body v-dialogDrag>
			<div class="userDialog">
				<div class="userLeft">
					<el-form :model="queryUser" ref="queryUser" size="small" :inline="true">
						<el-form-item label="工号" prop="userId">
							<el-input style="width: 220px" v-model="queryUser.userId" placeholder="请输入工号" maxlength="20" show-word-limit  />
						</el-form-item>
						<el-form-item>
							<el-button type="primary" icon="el-icon-search" size="mini" @click="handleQueryUser">搜索</el-button>
							<el-button icon="el-icon-refresh" size="mini" @click="resetQueryUser">重置</el-button>
						</el-form-item>
					</el-form>
					<el-table ref="leftTable" v-loading="loadinguser" :data="userList" @selection-change="handleSelectionUser" height="488px" border>
						<el-table-column type="selection" width="50" align="center" />
						<el-table-column label="序号" align="center" type="index" width="55" />
						<el-table-column label="工号" prop="userName" />
						<el-table-column label="姓名" prop="nickName" />
					</el-table>
					<pagination :total="usertotal" :page.sync="queryUser.pageNum" :limit.sync="queryUser.pageSize" @pagination="getlistUser" />
				</div>
				<div class="userCenter">
					<div @click="setRight"><i class="el-icon-right"></i></div>
					<div @click="setLeft"><i class="el-icon-back"></i></div>
				</div>
				<div class="userRight">
					<el-table :data="selectuserList" height="488px" ref="rightTable" @selection-change="handleBackUser" border>
						<el-table-column type="selection" width="50" align="center" />
						<el-table-column label="序号" align="center" type="index" width="55" />
						<el-table-column label="工号" prop="userName" />
						<el-table-column label="姓名" prop="nickName" />
						<el-table-column label="职位" prop="jobForemanFlag">
							<template slot-scope="scope">
								<div v-if="scope.row.jobForemanFlag == '1'">工段长</div>
								<div v-else>组员</div>
							</template>
						</el-table-column>
						<el-table-column label="操作" align="center" class-name="small-padding fixed-width">
							<template slot-scope="scope">
								<el-button size="mini" type="text" icon="el-icon-setting" @click="handleForemanFlag(scope.row)" v-if="scope.row.jobForemanFlag != '1'">设为工段长</el-button>
							</template>
						</el-table-column>
					</el-table>
				</div>
			</div>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="submitUser">确 定</el-button>
				<el-button @click="openUser = false">取 消</el-button>
			</div>
		</el-dialog>
		<el-dialog title="人员列表" :visible.sync="workopen" width="900px" append-to-body v-dialogDrag>
      <div style="height:70vh;overflow-y: auto;">
        <el-table :data="worklist" v-loading="loadingwork" border>
				<el-table-column label="序号" align="center" type="index" width="55" />
				<el-table-column label="工号" prop="userName" />
				<el-table-column label="姓名" prop="nickName" />
				<el-table-column label="职位" prop="jobForemanFlag">
					<template slot-scope="scope">
						<div v-if="scope.row.jobForemanFlag == '1'">工段长</div>
						<div v-else>组员</div>
					</template>
				</el-table-column>
			</el-table>
      </div>

		</el-dialog>
	</div>
</template>

<script>
import { getcolumn } from "@/api/selectList"
import { listUser, workUserlist, listWorkshopSection, getWorkshopSection, delWorkshopSection, addWorkshopSection, updateWorkshopSection } from "@/api/system/workshopSection"
export default {
	name: "WorkshopSection",
	dicts: ["default_status", "default_workcar"],
	data() {
		return {
			eleTabTop: 0, //表格容器距浏览器顶部距离
			querywork: { workshopSectionId: null },
			// 人员列表条数
			worktotal: 0,
			// 每行id
			shopSectionId: "",
			// 列表中人员列表
			loadingwork: false,
			// 列表中人员弹窗
			workopen: false,
			// 列表中人员列表
			worklist: [],
			// 右侧选中复选
			BackSelectionUser: [],
			// 左侧选中复选
			SelectionUser: [],
			// 选取的人员列表
			selectuserList: [],
			queryUser: {
				pageNum: 1,
				pageSize: 10,
				userName: null
			},
			loadinguser: false,
			// 人员条数
			usertotal: 0,
			// 人员弹窗左侧列表
			userList: [],
			// 人员弹窗显示
			openUser: false,
			// 遮罩层
			loading: true,
			// 选中数组
			ids: [],
			// 子表选中数据
			checkedTWorkshopSectionUser: [],
			// 非单个禁用
			single: true,
			// 非多个禁用
			multiple: true,
			// 显示搜索条件
			showSearch: true,
			// 总条数
			total: 0,
			// 工段表格数据
			workshopSectionList: [],
			// 工段人员表格数据
			tWorkshopSectionUserList: [],
			// 弹出层标题
			title: "",
			// 是否显示弹出层
			open: false,
			// 查询参数
			queryParams: {
				pageNum: 1,
				pageSize: 10,
				workshopId: null,
				workshopName: null,
				workshopSectionName: null,
				workshopSectionChiefId: null,
				workshopSectionChiefName: null,
				state: null,
				sort: null
			},
			// 表单参数
			form: { state: "1" },
			// 表单校验
			rules: {
				workshopId: [{ required: true, message: "生产车间不能为空", trigger: "change" }],
				workshopSectionName: [{ required: true, message: "工段名称不能为空", trigger: "blur" }]
			},
			// 列信息
			columns: [
				{ key: 0, label: `生产车间`, visible: true },
				{ key: 1, label: `工段名称`, visible: true },
				{ key: 2, label: `工段长`, visible: true },
				{ key: 3, label: `状态`, visible: true }
			]
		}
	},
	created() {
		this.getSize()
	},
	mounted() {
		// 滚动条的获取
		this.handleScrollx()
		window.addEventListener("scroll", this.handleScrollx, true)
	},
	activated() {
    this.getSize()
		//获取表格容器距页面头部的距离
		this.handleScrollx()
	},
	destroyed() {
		window.removeEventListener("scroll", this.handleScrollx, true)
	},
	methods: {
    getSize() {
			getcolumn({ pageName: "Pagination73" }).then(response => {
				this.queryParams.pageSize = response.data.length ? (response.data[0].limit ? response.data[0].limit : 10) : 10
				this.getList()
			})
		},
		// 单击表格行
		row_click(row, column, event) {
			if (column && column.label == "操作") {
				return
			} else {
				this.$refs.table.toggleRowSelection(row)
			}
		},
		changeTableData() {
			this.$nextTick(() => {
				this.$refs.table.doLayout()
			})
		},

		//获取表格容器距页面头部的距离
		handleScrollx() {
			this.eleTabTop = this.$refs.eleTab.getBoundingClientRect().top
		},
		// 提交人员
		submitUser() {
			let flag = this.selectuserList.some(item => item.jobForemanFlag == 1)
			if (flag) {
				updateWorkshopSection({
					id: this.shopSectionId,
					tworkshopSectionUserList: this.selectuserList
				}).then(res => {
					this.$modal.msgSuccess("设置成功")
					this.openUser = false
					this.getList()
				})
			} else {
				this.$modal.msgError("请先设置工段长")
			}
		},
		// 设置工段长
		handleForemanFlag(row) {
			this.selectuserList.forEach((item, index) => {
				if (row.userId == item.userId) {
					this.$set(item, "jobForemanFlag", 1)
				} else {
					this.$set(item, "jobForemanFlag", 0)
				}
				this.$forceUpdate()
			})
		},
		// 多选框选中数据
		handleSelectionUser(selection) {
			this.SelectionUser = selection
		},
		setRight() {
			this.SelectionUser.forEach(item => this.$set(item, "jobForemanFlag", 0))
			this.selectuserList.push(...this.SelectionUser)
			this.selectuserList = this.removeSame1(this.selectuserList)
			this.$refs.leftTable.clearSelection()
		},
		// 去重
		removeSame1(arr) {
			let map = new Map()
			for (let item of arr) {
				// map.has()方法判断map中是否存在这个键
				// 不存在，则将键和值同时设置到map集合中，
				if (!map.has(item.userId)) {
					map.set(item.userId, item)
				}
			}
			// 返回map的值
			return [...map.values()]
		},
		handleBackUser(selection) {
			this.BackSelectionUser = selection
		},
		setLeft() {
			this.BackSelectionUser.forEach(item => {
				this.selectuserList.forEach((items, index) => {
					if (item.userId == items.userId) {
						this.selectuserList.splice(index, 1)
					}
				})
			})
			// 删除设置的工段长、组员
			this.userList.forEach(item => {
				if (item.jobForemanFlag) {
					delete item.jobForemanFlag
				}
			})
		},
		// 更多操作触发
		handleCommand(command, row) {
			switch (command) {
				case "handleSetting":
					this.handleSetting(row)
					break
				case "handleUserList":
					this.handleUserList(row)
					break
				default:
					break
			}
		},
		/** 搜索按钮操作 */
		handleQueryUser() {
			this.queryUser.pageNum = 1
			this.getlistUser()
		},
		/** 重置按钮操作 */
		resetQueryUser() {
			this.resetUserS()
			this.handleQueryUser()
		},
		// 查询人员
		getlistUser() {
			this.loadinguser = true
			this.userList = []
			listUser(this.queryUser).then(response => {
				response.rows.forEach(item => {
					let obj = {}
					obj.userId = item.userId
					obj.userName = item.userName
					obj.nickName = item.nickName
					obj.workshopSectionId = this.shopSectionId
					this.userList.push(obj)
				})
				this.usertotal = response.total
				this.loadinguser = false
			})
		},
    resetUserS(){
      this.queryUser = {
        pageNum :1,
        pageSize:10,
        userId:undefined
      }
      this.resetForm("queryUser")
    },
		//  设置人员
		handleSetting(row) {
      this.resetUserS()
			this.selectuserList = []
			this.shopSectionId = row.id
			this.getlistUser()
			this.getworkUserlist(row.id)
			this.openUser = true
		},
		getworkUserlist(id) {
			this.loadingwork = true
			this.querywork.workshopSectionId = id
			workUserlist(this.querywork).then(res => {
				this.worklist = res.rows
				this.selectuserList = res.rows
				this.loadingwork = false
			})
		},
		//  人员列表
		handleUserList(row) {
			this.workopen = true
			this.getworkUserlist(row.id)
		},
		// 状态修改
		handleStatusChange(row) {
			this.$modal
				.confirm("确认要修改工段状态吗？")
				.then(function () {
					return updateWorkshopSection({
						id: row.id,
						state: row.state
					})
				})
				.then(() => {
					this.$modal.msgSuccess("修改成功")
				})
				.catch(function () {
					row.state = row.state === "0" ? "1" : "0"
				})
		},
		// 选择生产车间
		changeworkshop(e) {
			this.dict.type.default_workcar.forEach(element => {
				if (e == element.value) {
					this.form.workshopName = element.label
				}
			})
		},
		/** 查询工段列表 */
		getList() {
			this.loading = true
			listWorkshopSection(this.queryParams).then(response => {
				this.workshopSectionList = response.rows
				this.total = response.total
				this.loading = false
			})
		},
		// 取消按钮
		cancel() {
			this.open = false
			this.reset()
		},
		// 表单重置
		reset() {
			this.form = {
				id: null,
				workshopId: null,
				workshopName: null,
				workshopSectionName: null,
				workshopSectionChiefId: null,
				workshopSectionChiefName: null,
				state: "1"
			}
			this.tWorkshopSectionUserList = []
			this.resetForm("form")
		},
		/** 搜索按钮操作 */
		handleQuery() {
			this.queryParams.pageNum = 1
			this.getList()
		},
		/** 重置按钮操作 */
		resetQuery() {
			this.resetForm("queryForm")
			this.handleQuery()
		},
		// 多选框选中数据
		handleSelectionChange(selection) {
			this.ids = selection.map(item => item.id)
			this.single = selection.length !== 1
			this.multiple = !selection.length
		},
		/** 新增按钮操作 */
		handleAdd() {
			this.reset()
			console.log(this.form)
			this.open = true
			this.title = "添加工段"
		},
		/** 修改按钮操作 */
		handleUpdate(row) {
			this.reset()
			const id = row.id || this.ids
			getWorkshopSection(id).then(response => {
				this.form = response.data
				this.tWorkshopSectionUserList = response.data.tWorkshopSectionUserList
				this.open = true
				this.title = "修改工段"
			})
		},
		/** 提交按钮 */
		submitForm() {
			this.$refs["form"].validate(valid => {
				if (valid) {
					this.form.tWorkshopSectionUserList = this.tWorkshopSectionUserList
					if (this.form.id != null) {
						updateWorkshopSection(this.form).then(response => {
							this.$modal.msgSuccess("修改成功")
							this.open = false
							this.getList()
						})
					} else {
						addWorkshopSection(this.form).then(response => {
							this.$modal.msgSuccess("新增成功")
							this.open = false
							this.getList()
						})
					}
				}
			})
		},
		/** 删除按钮操作 */
		handleDelete(row) {
			const ids = row.id || this.ids
			this.$modal
				.confirm("是否确认删除工段数据项？")
				.then(function () {
					return delWorkshopSection(ids)
				})
				.then(() => {
					this.getList()
					this.$modal.msgSuccess("删除成功")
				})
				.catch(() => {})
		},
		/** 导出按钮操作 */
		handleExport() {
			this.download(
				"erp/workshopSection/export",
				{
					...this.queryParams
				},
				`workshopSection_${new Date().getTime()}.xlsx`
			)
		}
	}
}
</script>
<style scoped lang="scss">
.userDialog {
	display: flex;
	justify-content: space-between;
	align-items: center;
	.userLeft {
		width: 40%;
	}
	.userRight {
		width: 52%;
	}
	.userRight {
		padding-bottom: 3px;
	}
	.userCenter {
		> div:first-child {
			margin-bottom: 50px;
		}
		.el-icon-right,
		.el-icon-back {
			font-size: 30px !important;
		}
	}
}
</style>
